﻿<%@ WebHandler Language="C#" Class="CommissionScale" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using Chenxin.Lib.Utility;
using Chenxin.Lib.Business;
using Chenxin.Lib.Business.BLL;

public class CommissionScale : AjaxHandlerBase
{

    public CommissionScale()
    {
        //导出
        htTypePermit.Add("export", Constants.Permit_CommissionScale_Export);
        htTypePermit.Add("del", Constants.Permit_CommissionScale_Del);
        htTypePermit.Add("addscale", Constants.Permit_CommissionScale_Add);
        htTypePermit.Add("editscale", Constants.Permit_CommissionScale_Edit);
    }

    override public void RequestProcess(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";

            string strOp = context.Request["op"];
            string strRet = string.Empty;
            switch (strOp.ToLower())
            {
                case "getlist":
                    GetList(context);
                    break;
                case "del":             //删除设定
                    Del(context);
                    break;
                case "addscale":
                    AddScale(context);
                    break;
                case "editscale":
                    EditScale(context);
                    break;
                case "getmodel":
                    GetModel(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    private void GetModel(HttpContext context)
    {
        string modelid = context.Request["modelid"];
        Chenxin.Lib.Business.Entity.t_Bonus_RatioPara info = Chenxin.Lib.Business.DAL.t_Bonus_RatioPara.GetModel(new Guid(modelid));
        context.Response.Write(string.Format("{{success:'1',msg:'成功',data:{{model:{0}}}}}",
                 Chenxin.Lib.Utility.JsonHelp.Convert2Json(info)));
    }
    
    //编辑设定
    private void EditScale(HttpContext context)
    {
        try
        {
            Chenxin.Lib.Business.Entity.t_Bonus_RatioPara info =
            (Chenxin.Lib.Business.Entity.t_Bonus_RatioPara)JsonHelp.Convert2Entity(context.Request["model"],
                    typeof(Chenxin.Lib.Business.Entity.t_Bonus_RatioPara));

            string date = context.Request["AchievementDate"];
            info.AchievementYear =int.Parse(date.Substring(0, 4));
            info.AchievementMonth = int.Parse(date.Length > 6 ? date.Substring(5, 2).TrimStart('0') : date.Substring(5, 1));
            Chenxin.Lib.Business.DAL.t_Bonus_RatioPara.Update(info);
            
            context.Response.Write(string.Format("{{success:'1',msg:'编辑成功',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", ex.Message));
        }
    }
    
    //添加设定
    private void AddScale(HttpContext context)
    {
        try
        {
            string stime = context.Request["stime"];
            string etime = context.Request["etime"];

            decimal min = string.IsNullOrEmpty(context.Request["min"]) ? (decimal)0 : decimal.Parse(context.Request["min"].ToString());
            decimal max = string.IsNullOrEmpty(context.Request["max"]) ? (decimal)9999999999 : decimal.Parse(context.Request["max"].ToString());
            decimal Deduct = string.IsNullOrEmpty(context.Request["Deduct"]) ? (decimal)0 :decimal.Parse(context.Request["Deduct"].ToString());

            DateTime DateTime_s = DateTime.Parse(stime);
            DateTime DateTime_e = DateTime.Parse(etime);

            int count = (DateTime_e.Year - DateTime_s.Year) * 12 + (DateTime_e.Month - DateTime_s.Month);
            if (count < 0)
            {
                context.Response.Write(string.Format("{{success:'0',msg:'结束日期早于开始日期，操作失败！',data:''}}"));
                return;
            }
            
            for (int i = 0; i <= count; i++)
            {
                Chenxin.Lib.Business.Entity.t_Bonus_RatioPara info = new Chenxin.Lib.Business.Entity.t_Bonus_RatioPara();
                info.RecordId = Guid.NewGuid();
                info.CompanyId = CurrentUserInfo.CompanyId;
                info.AchievementsMin = min;
                info.AchievementsMax = max;
                info.Deduct = Deduct;
                info.AchievementYear = DateTime_s.AddMonths(i).Year;
                info.AchievementMonth = DateTime_s.AddMonths(i).Month;
                info.Ratio = decimal.Parse(context.Request["Ratio"].ToString());
                Chenxin.Lib.Business.DAL.t_Bonus_RatioPara.Add(info);
            }

            context.Response.Write(string.Format("{{success:'1',msg:'添加成功',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", ex.Message));
        }
    }

    //删除设定
    private void Del(HttpContext context)
    {
        try
        {
            string listid = context.Request.Params["modelid"];
            listid = listid.Replace(",", "','");
            string strSql = string.Format("delete t_Bonus_RatioPara where RecordId in ('{0}') ;", listid);
            Chenxin.Lib.Business.DAL.t_Bonus_RatioPara.ExecuteSQL(strSql);

            context.Response.Write(string.Format("{{success:'1',msg:'删除成功',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", ex.Message));
        }
    }
    

    private void GetList(HttpContext context)
    {
        Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
        Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);

        //判断权限范围/////////////////////////////////////////////
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        
        if (CurrentUserInfo.ContainsPermit(Constants.Permit_SearchCommissionScale_All))
        {
            sb.Append(" 1=1 ");
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_SearchCommissionScale_City))
        {
            sb.Append(" (EXISTS(");
            sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
            sb.AppendFormat("WHERE (CompanyId = M.Departid AND M.CityId='{0}'))) ", CurrentUserInfo.CityId);
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_SearchCommissionScale_Company))
        {
            sb.AppendFormat(" CompanyId='{0}' ", CurrentUserInfo.CompanyId);
        }
        else
        {
            sb.Append(" 1=0 ");
        }
        
        if (company != Guid.Empty)
        {
            sb.AppendFormat(" and CompanyId='{0}' ", company);
        }
        else if (city != Guid.Empty)
        {
            sb.Append(" AND (EXISTS(");
            sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
            sb.AppendFormat("WHERE (CompanyId = M.Departid AND M.CityId='{0}'))) ", city);
        }
        else
            sb.AppendFormat(" AND CompanyId='{0}' ", CurrentUserInfo.CompanyId);


        if (!String.IsNullOrEmpty(context.Request.Params["Addtime"]))
        {
            sb.AppendFormat(" And ((AchievementYear={0} And AchievementMonth >={1}) or (AchievementYear>{0}))",  context.Request["Addtime"].Substring(0, 4),context.Request["Addtime"].Length > 6 ? context.Request["Addtime"].Substring(5, 2).TrimStart('0') : context.Request["Addtime"].Substring(5, 1));
        }
        if (!String.IsNullOrEmpty(context.Request.Params["Endtime"]))
        {
            sb.AppendFormat(" And ((AchievementYear={0} And AchievementMonth <={1}) or (AchievementYear<{0})) ", context.Request["Endtime"].Substring(0, 4), context.Request["Endtime"].Length > 6 ? context.Request["Endtime"].Substring(5, 2).TrimStart('0') : context.Request["Endtime"].Substring(5, 1));
            
        }
        
        //页码
        int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
        //页显示行数
        int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 50 : int.Parse(context.Request["pagesize"]);//页记录数
        string strOrderField = "AchievementYear,AchievementMonth,AchievementsMin asc";
        DataSet ds = Chenxin.Lib.Business.DAL.t_Bonus_RatioPara.GetList(strPageIndex, strPageSize, strOrderField, "t_Bonus_RatioPara", sb.ToString(), "*", "*,dbo.FN_GetDepartNameByDepartID(CompanyId) as Company", true);

        context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[1].Rows[0][0], Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0]))); 
    }
}